<?php

namespace App\Services;

use Fukuball\Jieba\Finalseg;
use Fukuball\Jieba\Jieba;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class UtilService extends BaseServices
{
    private $init = false;

    public function generateObj()
    {
        return json_decode("{}");
    }


    public function isPhone($value)
    {
        return !!preg_match('/^(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/', $value);
    }

    public function is_email($value)
    {
        return !!preg_match('/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i', $value);
    }


    /**
     * 处理事务
     * @param $callback
     * @param bool $debug
     * @return bool
     */
    public function transaction($callback, $debug = true)
    {
        try {
            DB::transaction($callback, 5);

            return true;
        } catch (\Exception $exception) {
            if ($debug)
                Log::error("transaction error", [$exception]);

            return false;
        } catch (\Throwable $e) {
            if ($debug)
                Log::error("transaction error", [$e]);
            return false;
        }
    }


    public function str_to_utf8($str = '')
    {
        $current_encode = mb_detect_encoding($str, array("ASCII", "GB2312", "GBK", 'BIG5', 'UTF-8', "EUC-CN"));
        $encoded_str = mb_convert_encoding($str, 'UTF-8', $current_encode);
        return $encoded_str;
    }

    public function isUrl($url): bool
    {
        $components = parse_url($url);
        if (!isset($components['host']) || !isset($components['scheme'])) {
            return false;
        }
        if (!in_array($components['scheme'], ["http", 'https'])) {
            return false;
        }
        return true;
    }

    public function array_to_object($arr)
    {
        if (gettype($arr) != 'array') {
            return $arr;
        }
        foreach ($arr as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object') {
                $arr[$k] = (object)self::array_to_object($v);
            }
        }

        return (object)$arr;
    }


    public function leftFill($val, $len = 2, $fillStr = "0"): string
    {
        return str_pad($val, $len, $fillStr, STR_PAD_LEFT);
    }

//    public  function tokenize($v): array
//    {
//        $tokenizer = new PhpAnalysisTokenizer();
//        return $tokenizer->tokenize($v);
//    }


    /**
     * @param $url
     * @param $options
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function http_get($url, $options = []): \Psr\Http\Message\ResponseInterface
    {
        $client = new Client([\GuzzleHttp\RequestOptions::VERIFY => false]);
        return $client->request('GET', $url, array_merge($options, ['timeout' => 20]));
    }

    public function print($s)
    {
        echo "$s\n";
    }

    public function tokenizer($s, $min = 2): array
    {
        $text=str_replace(['"',",","?","!","<"],"",$s);
        if (!$this->init) {
            $this->init = true;
            Jieba::init();
            Finalseg::init();
        }
        $seg_list = Jieba::cut($text);
        $arr = [];
        foreach ($seg_list as $item) {
            if (mb_strlen($item) >= $min) {
                $arr[] = $item;
            }
        }
        return $arr;

    }


}